// pages/product/productDetails.js
var Zan = require('../../dist/index');
var WxParse = require('../../wxParse/wxParse.js');
let WxNotificationCenter = require('../../utils/WxNotificationCenter.js');
var network = null;
var utils = null;
var api = null;
const app = getApp();
var eventStatus = 0; // 0=没选规格;1=加入购物车;2=立即购买
var start1 = 0;
Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    product: {},
    listSpec: [],
    showDialog: false,
    count: 0,
    currProPrice: 0,
    memberPrice: 0,
    oldPrice: 0,
    selectedSpec: null,
    num: 0,
    shopCarDialog: false,
    items: [],
    specId: null,
    store:[],
    storeId: null,
    // TenantDistribution: null,
    specArr: [],
    specArrCon: [],
    specArray:[],
    title: '',
    limitCount: 0,
    storeCount: 0,
    batting: false,
    itemsCount: 0,
    isSharetuan:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();
    if (options.storeInfo) {
      app.globalData.store = JSON.parse(decodeURIComponent(options.storeInfo))
    }
    if (!app.globalData.store){
      let that = this;
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          let latitude = res.latitude;
          let longitude = res.longitude;
          that.setData({
            lng: longitude,
            lat: latitude
          })
          network._post_json(that, api.nearbyStore, { lng: longitude, lat: latitude }, successStore);
        },
        fail: function (res) {
          console.log("拒绝获取地理位置++++++++++++++++++");
          that.setData({
            lng: 114.31171,
            lat: 30.59868
          })
          network._post_json(that, api.nearbyStore, { lng: that.data.lng, lat: that.data.lat }, successStore);
        }
      })
    }
    this.setData({
      productId: options.productId,
      store: app.globalData.store,
      bananer: {
        autoplay: true,
        interval: 5000,
        duration: 300,
        indicatorDots: true,
        circular: true,
        height: utils.windowSize().winWidth / 750 * 560
      },
      videoHeight: utils.windowSize().winWidth / 750 * 402
    })

    if (app.globalData.userId) {
      bind(options);
    } else {
      // 由于 openId 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoCallback = res => {
        bind(options);
      }
    }

    wx.showShareMenu({
      withShareTicket: true //要求小程序返回分享目标信息
    })

    network._post_json(this, api.getProductDetails, { productId: options.productId }, success);
    // network._post_json(this, api.getTenantDistribution, { tenantId: app.globalData.tenantId, storeId: this.data.store.id }, successDistribution);
    getNowFormatDate(this);
    if (options.shared) {
      //存在shared表示别人分享过来的
      console.log('============shared==============');
      this.setData({
        isSharetuan: 1
      })
    }
    
    // 注册列表刷新事件
    WxNotificationCenter.addNotification("productRefreshNotification", this.refreshNotification, this);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      items: []
    })
    network._post_page_json(this, api.getShoppingCartList, start1, { userId: app.globalData.userId, storeId: app.globalData.store.id }, successCar);
    this.setData({
      count: 0,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    eventStatus = 0;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    WxNotificationCenter.removeNotification("productRefreshNotification", this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  refreshNotification: function () {
    console.log("==============api.getProductDetails===============");
    network._post_json(this, api.getProductDetails, { productId: this.data.product.id }, success);
    console.log("==============api.getShoppingCartList===============");
    this.setData({
      items: []
    })
    network._post_page_json(this, api.getShoppingCartList, start1, { userId: app.globalData.userId, storeId: app.globalData.store.id }, successCar);
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    return {
      title: this.data.product.title,
      path: '/pages/product/ProductDetails?shared=' + app.globalData.userInfo.id + '&productId=' + this.data.product.id + '&storeInfo=' + encodeURIComponent(JSON.stringify(app.globalData.store)),
      imageUrl: this.data.product.imgUrl,
      success: function (res) {
        //转发成功
        // if (res.shareTickets) {
        //   wx.getShareInfo({
        //     shareTicket: res.shareTickets,
        //     success: function (res) {
        //       network._post_json(that, api.updateFxcs, { directShareNums: 0, directShareQunNums: 1 }, fxcsSuccess);
        //     },
        //     fail: function (res) {
        //       // 转发失败
        //       network._post_json(that, api.updateFxcs, { directShareNums: 1, directShareQunNums: 0 }, fxcsSuccess);
        //     }
        //   })
        // } else {
        //   network._post_json(that, api.updateFxcs, { directShareNums: 1, directShareQunNums: 0 }, fxcsSuccess);
        // }

      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  gohome:function(){
    wx.switchTab({
      url: '/pages/home/Home',
    })
  },
  NoProduct:function(e){
    this.showZanTopTips(this.prompt, "购物车是空的");
  },
  /**
   * 弹出框开关
   */
  Specclose: function (e) {
    this.setData({
      specDialog: !this.data.specDialog,
    })
  },
  shopCarDialog: function (e) {
    this.setData({
      shopCarDialog: !this.data.shopCarDialog
    })
  },

  //购物车列表
  shopCarList: function (e) {
    if (this.data.shopCarDialog){

    }else{
      start1 = 0;
      this.setData({
        items: [],
      });
      network._post_page_json(this, api.getShoppingCartList, start1, { userId: app.globalData.userId, storeId: app.globalData.store.id }, successCar);
    }
    this.setData({
      shopCarDialog: !this.data.shopCarDialog
    })
  },
  /**
   * 进入下一步提交订单
   */
  pay: function (e) {
    getNowFormatDate(this);
    //校验数量
    for (let c = 0; c < this.data.items.length; c++) {
      var checkFlag = isSelectedOk2(this, this.data.items[c], this.data.items.count);
      if (checkFlag == -1) {
        this.showZanTopTips(this.prompt, "库存不足");
      } else if (checkFlag == -2) {
        this.showZanTopTips(this.prompt, "购买数量大于限购数量");
      }
    }
    // 商品
    let products = [];
    let count = 1;
    for (var i = 0; i < this.data.items.length; i++) {
      let product = {};
      let car = this.data.items[i];
      product.carid = car.id;
      product.id = car.productId;
      product.title = car.product.title;
      product.imgUrl = car.product.imgUrl;
      if (car.Productspecgroups){
        product.price = car.Productspecgroups.currentPrice;
        product.memberPrice = car.Productspecgroups.memberPrice;
      }else{
        product.price = car.product.currentPrice;
        product.memberPrice = car.product.memberPrice;
      }
      product.count = car.count;
      if (car.product.isService == 1) {
        product.isService = "1";
      }
      if (car.Productspecgroups) {
        let name = "";
        if (car.Productspecgroups.specDetails1) {
          name += car.Productspecgroups.specDetails1;
        }
        if (car.Productspecgroups.specDetails2) {
          name += '+' + car.Productspecgroups.specDetails2;
        }
        if (car.Productspecgroups.specDetails3) {
          name += '+' + car.Productspecgroups.specDetails3;
        }
        product.specId = car.Productspecgroups.id;
        product.specName = name;
      }
      products.push(product);
      count += parseInt(car.count);
    }
    wx.navigateTo({
      url: '/pages/pay/Pay?shoppingCar=' + encodeURIComponent(JSON.stringify(products)) + '&store=' + encodeURIComponent(JSON.stringify(this.data.store))
    })

  },

  /**
   * 减商品数量
   */
  reduce: function (e) {
    if (this.data.count > 0) {
      this.data.count--;
      for (var c = 0; c < this.data.items.length; c++) {
        if (this.data.items[c].productId == this.data.product.id) {
          this.data.items[c].count = '' + this.data.count + ''
        }
      }
      this.setData({
        count: this.data.count,
        items: this.data.items
      });
      addShoppingCart(this, this.data.product);
      calcPoint(this);
    }
  },
  /**
   * 加商品数量
   */
  add: function (e) {
    if (this.data.product.isVirtual == 1){
      this.showZanTopTips(this.prompt, "该商品为虚拟模板商品不能购买");
    }else{
      var counts = parseInt(this.data.count) + 1;
      // this.data.count++;
      for (var c = 0; c < this.data.items.length; c++) {
        if (this.data.items[c].productId == this.data.product.id) {
          this.data.items[c].count = '' + this.data.count + ''
        }
      }
      //校验数量
      var checkFlag = isSelectedOk(this, this.data.product, counts);
      if (checkFlag == -1) {
        this.showZanTopTips(this.prompt, "库存不足");
        return false;
      } else if (checkFlag == -2) {
        this.showZanTopTips(this.prompt, "购买数量大于限购数量");
        return false;
      } else {
        this.data.count++;
        this.setData({
          count: this.data.count,
          items: this.data.items
        });
        addShoppingCart(this, this.data.product);
        calcPoint(this);
      }
    }
  },
  /**
   * 多规格，减商品数量
   */
  reduceTips:function(e){
    this.showZanTopTips(this.prompt,'多规格商品只能在购物车删除');
  },
  reduce2: function (e) {
    if (this.data.count > 1) {
      this.data.count--;
      // this.data.currentPrice = this.data.product.currentPrice * this.data.count;
      this.setData({
        count: this.data.count,
      });
    }
  },

  /**
  * 多规格，加商品数量
  */
  add2: function (e) {
    
    var counts = parseInt(this.data.count) + 1;
    // this.data.count++;
    //校验数量
    var checkFlag = isSelectedOk(this, this.data.product, counts);
    if (checkFlag == -1) {
      this.showZanTopTips(this.prompt, "库存不足");
      return false;
    } else if (checkFlag == -2) {
      this.showZanTopTips(this.prompt, "购买数量大于限购数量");
      return false;
    } else {
      this.data.count++;
      this.setData({
        count: this.data.count,
      });
    }


    
  },
  /**
   * 购物车，减商品数量
   */
  reduce3: function (e) {
    var itemCon = e.currentTarget.dataset.item;
    var itemIdx = e.currentTarget.dataset.index;
    if (itemCon.count > 0) {
      itemCon.count--;
      this.data.items[itemIdx] = itemCon;
      if (this.data.items[itemIdx].productId == this.data.product.id) {
        this.data.count = this.data.items[itemIdx].count
      }
      this.setData({
        product: this.data.product,
        items: this.data.items
      });

      addShoppingCart2(this, this.data.items[itemIdx]);
      allPrice(this, this.data.items);
    }
  },

  /**
   * 购物车，加商品数量
   */
  add3: function (e) {
    var itemCon = e.currentTarget.dataset.item;
    var itemIdx = e.currentTarget.dataset.index;
    var counts = parseInt(itemCon.count) + 1;
    // itemCon.count++;

    //校验数量
    var checkFlag = isSelectedOk2(this, this.data.items[itemIdx], counts);
    if (checkFlag == -1) {
      this.showZanTopTips(this.prompt, "库存不足");
      return false;
    } else if (checkFlag == -2) {
      this.showZanTopTips(this.prompt, "购买数量大于限购数量");
      return false;
    } else {
      
      this.data.items[itemIdx].count++;
      if (this.data.items[itemIdx].productId == this.data.product.id) {
        this.data.count = this.data.items[itemIdx].count
      }
      this.setData({
        product: this.data.product,
        items: this.data.items
      });
      addShoppingCart2(this, this.data.items[itemIdx]);
      allPrice(this, this.data.items);
    }

    
  },
  /**
   * 如果用户已授权，并且用户昵称不为空，则直接弹框
   */
  chooseSpan: function (e) {
    //if (this.data.product.isVirtual == 0 && this.data.product.isActive == 1) {
    if (this.data.count <= 0) {
      this.showZanTopTips(this.prompt, "请选择数量");
    } else {
      addShoppingCart(this, this.data.product);
    }
    //当前已经选好，直接购买
    
  },

  formSubmit: function (e) {
    this.setData({
      formId: e.detail.formId
    })
  },

  getPhoneNumber: function (e) {
    if (e.detail.encryptedData) {
      network._post_json(this, api.wxphone, { encryptedData: e.detail.encryptedData, iv: e.detail.iv, sessionKey: app.globalData.sessionKey }, bindSuccess);
    }
  },


  //规格显示
  selectSpec: function (e) {
    var title = e.currentTarget.dataset.title;
    var productId = e.currentTarget.dataset.id;
    this.data.specArr = JSON.parse(this.data.product.spec);

    let specArrCon = [];
    for (var n = 0; n < this.data.specArr.length; n++) {
      let spec = {};
      let specDetailArr = [];
      spec.specType = this.data.specArr[n].specType;
      for (var i = 0; i < this.data.specArr[n].specDetails.length; i++) {
        let specDetail = {};
        specDetail.name = this.data.specArr[n].specDetails[i];
        specDetail.class = '';
        if (i == 0) {
          specDetail.class = "active";
        }
        specDetailArr.push(specDetail);
      }
      specArrCon.push(spec);
      spec.specDetails = specDetailArr;
    }

    this.setData({
      specTitle: title,
      specArrCon: specArrCon,
      specDialog: !this.data.specDialog,
      productId: productId,
      specDetails1: specArrCon[0].specDetails[0].name,
      specDetails2: specArrCon[1] != undefined?specArrCon[1].specDetails[0].name:'',
      specDetails3: specArrCon[2] != undefined ? specArrCon[2].specDetails[0].name:'',
      currProPrice: this.data.currProPrice

    })

    getProductPrice(this);
  },
  //选择一个规格后
  specSelect: function (e) {
    console.log(this.data.specArrCon);
    var currData = e.currentTarget.dataset;
    var fatidx = currData.fatidx;
    var subidx = currData.subidx;
    var currBind = this.data.specArrCon[fatidx].specDetails[subidx];
    currBind.class = "active";

    //处理当前选择的规格类型的其他规格
    for (var n = 0; n < this.data.specArrCon[fatidx].specDetails.length; n++) {
      if (this.data.specArrCon[fatidx].specDetails[n].class == "active" && subidx != n) {
        this.data.specArrCon[fatidx].specDetails[n].class = "";
      }
    }

    this.setData(this.data);
    //计算所选规格价格
    var selectedSpec = [];
    for (var m = 0; m < this.data.specArrCon.length; m++) {
      for (var n = 0; n < this.data.specArrCon[m].specDetails.length; n++) {
        if (this.data.specArrCon[m].specDetails[n].class == "active") {
          selectedSpec.push(this.data.specArrCon[m].specDetails[n].name);
        }
      }
    }

    this.setData({
      specDetails1: selectedSpec[0],
      specDetails2: selectedSpec[1] != undefined ? selectedSpec[1]:'',
      specDetails3: selectedSpec[2] != undefined ? selectedSpec[2]:'',
    })
    getProductPrice(this);
  },

  startPlay: function (e) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        if (res.system.indexOf("iOS") >= 0) {
          let id = e.target.dataset.id;
          wx.createVideoContext(id).play();
          wx.createVideoContext(id).pause();
        }
      }
    })
  },

  not: function (e) {
    let id = e.target.dataset.id;
    wx.createVideoContext(id).play();
    wx.createVideoContext(id).pause();
  },
  alldel: function (e) {
    let allProId = [];
    for (var c = 0; c < this.data.items.length; c++) {
      let ProIdItems = this.data.items[c].id;
      allProId.push(ProIdItems);
    }
    allProId = allProId.join(',');
    console.log("确定清空吗？");
    console.log(allProId);
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定清空吗？',
      success: function (res) {
        if (res.confirm) {
          network._post_json(that, api.delShoppingCart, { shoppingCarId: allProId, is_del: 1 }, delSuccess);
          that.setData({
            shopCarDialog: !that.data.shopCarDialog,
            count:0
          })


        } else if (res.cancel) {
        }
      }
    })
  }
}))
//Page结束
//门店
var successStore = function (that, res) {
  if (res.data.data) {
    that.setData({
      store: res.data.data,
    })
    app.globalData.store = res.data.data
  }
}
//计算当前价格
var calcPoint = function (that) {
  //多规格
  that.setData({
    currProPrice: that.data.product.currentPrice
  })
}
//校验当前选择的规格及数量是否可以购买
var isSelectedOk = function (that, product, counts) {
  //多规格
  if (product.specClass == 2) {
    if (that.data.isStore == 0) {
      if (that.data.limitCount != 0) {
        if (counts > that.data.limitCount) {
          //数量超出限购数量
          return -2;
        }
        return 1;
      }
      return 1;
    } else {
      if (that.data.limitCount != 0) {
        if (that.data.storeCount <= 0 || that.data.storeCount < counts) {
          //库存不足
          return -1;
        } else if (counts > that.data.limitCount) {
          //数量超出限购数量
          return -2;
        } else {
          return 1;
        }
      } else {
        if (that.data.storeCount <= 0 || that.data.storeCount < counts) {
          //库存不足
          return -1;
        } else {
          return 1;
        }
      }
    }
  } else {
    if (product.isStore == 0) {
      if (product.limitCount != 0) {
        if (counts > product.limitCount) {
          //数量超出限购数量
          return -2;
        }
        return 1;
      }
      return 1;
    } else {
      if (product.limitCount != 0) {
        if (product.storeCount <= 0 || product.storeCount < counts) {
          //库存不足
          return -1;
        } else if (counts > product.limitCount) {
          //数量超出限购数量
          return -2;
        } else {
          return 1;
        }
      } else {
        if (product.storeCount <= 0 || product.storeCount < counts) {
          //库存不足
          return -1;
        } else {
          return 1;
        }
      }

    }
  }
}
//校验购物车当前选择的规格及数量是否可以购买
var isSelectedOk2 = function (that, product, counts) {
  //多规格
  if (product.product.specClass == 2) {
    if (product.Productspecgroups.isStore == 0) {
      if (product.Productspecgroups.limitCount != 0) {
        if (counts > product.Productspecgroups.limitCount) {
          //数量超出限购数量
          return -2;
        }
        return 1;
      }
      return 1;
    } else {
      if (product.Productspecgroups.limitCount != 0) {
        if (product.Productspecgroups.storeCount <= 0 || product.Productspecgroups.storeCount < counts) {
          //库存不足
          return -1;
        } else if (counts > product.Productspecgroups.limitCount) {
          //数量超出限购数量
          return -2;
        } else {
          return 1;
        }
      } else {
        if (product.Productspecgroups.storeCount <= 0 || product.Productspecgroups.storeCount < counts) {
          //库存不足
          return -1;
        } else {
          return 1;
        }
      }

    }
  } else {
    if (product.product.isStore == 0) {
      if (product.product.limitCount != 0) {
        if (counts > product.product.limitCount) {
          //数量超出限购数量
          return -2;
        }
        return 1;
      }
      return 1;
    } else {
      if (product.product.limitCount != 0) {
        if (product.product.storeCount <= 0 || product.product.storeCount < counts) {
          //库存不足
          return -1;
        } else if (counts > product.product.limitCount) {
          //数量超出限购数量
          return -2;
        } else {
          return 1;
        }
      } else {
        if (product.product.storeCount <= 0 || product.product.storeCount < counts) {
          //库存不足
          return -1;
        } else {
          return 1;
        }
      }

    }

  }
}
// 获取商品列表结果
var success = function (that, res) {
  if (res.data.data) {
    that.setData({
      product: res.data.data,
      currProPrice: res.data.data.currentPrice,
      memberPrice: res.data.data.memberPrice,
      detail: res.data.data.detail.replace(/\<img/gi, '<img style="width:100%;height:auto" ').replace(/\white-space: nowrap;/gi, '').replace(/\white-space:nowrap;/gi, '')
    
    })
    
    // WxParse.wxParse('details', 'html', res.data.data.detail, that, 0);
    network._post_page_json(that, api.getShoppingCartList, start1, { userId: app.globalData.userId, storeId: app.globalData.store.id }, successCar);
  }
}
// var successDistribution = function (that, res) {
//   if (res.data.data) {
//     that.setData({
//       TenantDistribution: res.data.data
//     })
//   }
// }
var successCar = function (that, res) {
  that.setData({
    itemsCount: 0,
    items:[]
  })
  if (res.data.data) {
    for (var c = 0; c < res.data.data.list.length; c++) {
      that.data.itemsCount += parseInt(res.data.data.list[c].count);
      if (res.data.data.list[c].product.specClass == 2) {
        if (!res.data.data.list[c].Productspecgroups) {
          network._post_json(that, api.delShoppingCart, { shoppingCarId: res.data.data.list[c].id, is_del: 0 }, delSuccess);
        }
      }
    }
    that.setData({
      items: res.data.data.list,
      itemsCount: that.data.itemsCount
    })
    // console.log(that.data.items);
    for (var c = 0; c < that.data.items.length; c++) {
      if (that.data.items[c].productId == that.data.product.id) {
        that.data.count = that.data.items[c].count
      }
    }
    that.setData({
      count: that.data.count,
      // specArray: that.data.specArray
    })
    console.log(that.data.currProPrice);
    allPrice(that, res.data.data.list)
  }
}
/**
 * 计算购物车商品的总价
 */
var allPrice = function (that, items) {
  var oldPrice = 0;
  if (items.length != 0) {
    for (var i = 0; i < items.length; i++) {
      if (items[i].Productspecgroups) {
        oldPrice += items[i].Productspecgroups.currentPrice * items[i].count;
      } else {
        oldPrice += items[i].product.currentPrice * items[i].count;
      }
    }

    // if (that.data.TenantDistribution.logistics) {
    //   oldPrice = oldPrice + parseInt(that.data.TenantDistribution.logistics.packingCharge)
    // } else if (that.data.TenantDistribution.pickedUp) {
    //   oldPrice = oldPrice + parseInt(that.data.TenantDistribution.pickedUp.packingCharge)
    // }

    that.setData({
      oldPrice: oldPrice
    })
    
  } else {
    that.setData({
      oldPrice: 0
    })
  }

}
var addSuccess = function (that, res) {
  network._post_page_json(that, api.getShoppingCartList, start1, { userId: app.globalData.userId, storeId: app.globalData.store.id }, successCar);
  that.showZanToast('添加成功');
}
//商品详情添加修改购物车
var addShoppingCart = function (that, products) {

  // if (that.data.product.isVirtual == 0 && that.data.product.isActive == 1) {
    //多规格
  if (products.specClass == 2) {
    network._post_json(that, api.addShoppingCart, { productId: products.id, specId: that.data.specId, count: that.data.count, storeId: that.data.store.id, userId: app.globalData.userId }, addSuccess);
    that.setData({
      specDialog: !that.data.specDialog
    })
  } else {
    // 没有规格的商品
    network._post_json(that, api.addShoppingCart, { productId: products.id, count: that.data.count, storeId: that.data.store.id, userId: app.globalData.userId }, addSuccess);
  }
  
  
  // } else {
  //   that.showZanTopTips(that.prompt, '商品已下架');
  // }
}
//购物车列表添加修改
var addShoppingCart2 = function (that, items) {
  // console.log(items);
  //多规格
  if (items.product.specClass == 2) {
    network._post_json(that, api.addShoppingCart, { productId: items.product.id, specId: items.specId, count: items.count, storeId: that.data.store.id, userId: app.globalData.userId }, addSuccess);
  } else {
    // 没有规格的商品
    network._post_json(that, api.addShoppingCart, { productId: items.product.id, count: items.count, storeId: that.data.store.id, userId: app.globalData.userId }, addSuccess);
  }

  // } else {
  //   that.showZanTopTips(that.prompt, '商品已下架');
  // }
}
//获取多规格商品分类价格
var getProductPrice = function (that) {
  // console.log("获取多规格商品分类价格");
  console.log(that.data.product);
  
  //价格
  network._post_json(that, api.getProductPrice, { productId: that.data.product.id, specDetails1: that.data.specDetails1, specDetails2: that.data.specDetails2, specDetails3: that.data.specDetails3 }, successPrice);
}
var successPrice = function (that, res) {
  that.setData({
    count: 0
  })
  
  if (res.data.data) {
    for (var c = 0; c < that.data.items.length; c++) {
      if (that.data.items[c].specId == res.data.data.specId) {
        that.data.count = that.data.items[c].count;
        that.setData({
          count: that.data.count
        })
      }
    }
    that.setData({
      currProPrice: res.data.data.currentPrice ? res.data.data.currentPrice : 0,
      memberPrice: res.data.data.memberPrice ? res.data.data.memberPrice : 0,
      specId: res.data.data.specId,
      limitCount: res.data.data.limitCount,
      storeCount: res.data.data.storeCount,
      isStore: res.data.data.isStore

    })
    
  }
}
// var startPay = function (that) {
//   var product = {};
//   var products = [];
//   product.id = that.data.product.id;
//   product.title = that.data.product.title;
//   product.smallImgUrl = that.data.product.smallImgUrl;
//   product.count = that.data.count;

//   //多规格
//   if (that.data.product.specClass == 2) {
//     product.price = that.data.currProPrice / that.data.count * 100;
//     product.specId = that.data.selectedSpecRow.id;
//     product.specName = that.data.selectedSpecNames.join();
//     product.selectedSpec = that.data.selectedSpecRow;

//     console.log('huanghe');
//     console.log(that.data.selectedSpecNames)
//     console.log(product.specName)

//   } else {
//     // 没有规格的商品
//     product.price = that.data.product.price;
//   }

//   products.push(product);
//   try {
//     wx.setStorageSync('products', products)
//   } catch (e) {
//   }

//   wx.navigateTo({
//     url: '/pages/pay/Pay'
//   })
// }

var bindSuccess = function (that, res) {
  if (that.data.formId && app.globalData.userAndTenantInfo.mobile != res.data.data.mobile) {
    network._post_json(that, api.sendCoupn, { formId: that.data.formId, type: 2 }, sendCoupnSuccess);
  }

  app.globalData.userAndTenantInfo.mobile = res.data.data.mobile;
  that.setData({
    mobile: res.data.data.mobile
  })
}

var fxcsSuccess = function (that, res) {
  that.showZanToast('分享成功');
}

var bind = function (options) {
  if (options.shared) {
    wx.request({
      url: api.bindUserFormQRcode,
      data: {
        openId: app.globalData.openId,
        userId: app.globalData.userId,
        tenantId: app.globalData.tenantId,
        distributorId: options.shared,
        productId: options.productId
      },
      method: 'POST',
      success: function (res) {
      }
    });
  }
}
var delSuccess = function (that, res) {
  if (res.data.data) {
    network._post_page_json(that, api.getShoppingCartList, start1, { userId: app.globalData.userId, storeId: app.globalData.store.id }, successCar);
    that.onPullDownRefresh();
  }
}
var getNowFormatDate = function (that) {
  console.log("=========打烊getNowFormatDate==========");
  var date = new Date();
  var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
  var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
  var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  var currentdate = h + ":" + m + ":" + s;
  console.log(that.data.store);
  if (that.data.store.openTime > currentdate || that.data.store.closeTime < currentdate) {
    that.setData({
      batting: true
    })
  } else {
    that.setData({
      batting: false
    })
  }
}
var sendCoupnSuccess = function (that, res) { }